package com.example.demo1.webapi;

import org.apache.commons.lang.StringUtils;

import com.example.demo1.core.PageUtils;
import com.example.demo1.domain.Student;
import com.example.demo1.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;


import java.util.List;

@RestController
@RequestMapping("/webapi/student")
public class StudentRestController {

    @Autowired
    private StudentService studentService;

    /**
     * 读取的url：/webapi/student/list
     * @return
     */
    @GetMapping("/list")
    public List<Student> getAll() {
        List<Student> students = studentService.findAll();
        return students;
    }
    @PostMapping("/insert")
    public Student insert(Student student) {
        return studentService.insert(student);
    }

    @GetMapping("/get/{id}")
    public Student get(@PathVariable Integer id){
        return studentService.findById(id);
    }
    @PutMapping("/update/list")
    public Student update(Student student){
        return studentService.update(student);
    }

    @DeleteMapping("/delete/{id}")
    public void deleteStu(@PathVariable Integer id){
        studentService.deleteById(id);
    }

    /**
     * 分页，读取全部内容
     * @return
     */
    @GetMapping("/getByPage")
    public PageUtils getByPage(@RequestParam(value = "page",defaultValue = "0")Integer page,
                               @RequestParam(value = "size",defaultValue = "10")Integer size,
                               @RequestParam(value = "name",defaultValue = "")String name)

    {
        Page<Student> studentPage;
        //按照id排倒序
        if (StringUtils.isEmpty(name)){
            Pageable pageable = PageRequest.of(page,size,Sort.by("id").descending());
            studentPage = studentService.findAll(pageable);
        }else {
            Student student = new Student();
            student.setName(name);
            Pageable pageable = PageRequest.of(page,size,Sort.by("id").descending());
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("name",ExampleMatcher.GenericPropertyMatchers.contains());
            Example<Student> example = Example.of(student,matcher);
            studentPage = studentService.findAll(example,pageable);
        }

        PageUtils pageUtils = new PageUtils(studentPage.getContent(), studentPage.getTotalElements());
        return pageUtils;
    }

}






